package cn.com.yusys.yusp.admin.web.rest;

import cn.com.yusys.yusp.commons.file.FileManagementClientFactory;
import com.ctrip.framework.apollo.core.utils.StringUtils;
import cn.com.yusys.yusp.admin.domain.NetworkLiabilityStatementsPojo;
import cn.com.yusys.yusp.admin.service.NetworkLiabilityStatementsService;
import cn.com.yusys.yusp.commons.excel.ExcelConstant;
import cn.com.yusys.yusp.commons.excel.ExcelImportExportUtil;
import cn.com.yusys.yusp.commons.excel.ExcelTaskManager;
import cn.com.yusys.yusp.commons.file.FileManagementClient;
import cn.com.yusys.yusp.commons.mapper.QueryModel;
import cn.com.yusys.yusp.commons.web.rest.dto.ResultDto;
import groovy.json.JsonException;
import org.json.JSONObject;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.*;

@RestController
@RequestMapping("/api/NetworkLiabilityStatementsResource")
public class NetworkLiabilityStatementsResource {
    @Resource
    NetworkLiabilityStatementsService networkLiabilityStatementsService;

    @Resource
    private ExcelTaskManager excelTaskManager;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private FileManagementClientFactory fileManagementClientFactory;

    private String pojoClassName = NetworkLiabilityStatementsPojo.class.getName();
    private String exportSql = "getNetworkLiabilityStatementsInfo";

    @GetMapping("/getNetworkLiabilityStatementsInfo")
    public ResultDto<List<Map<String, Object>>> getNetworkLiabilityStatementsInfo(QueryModel queryModel) {
        CustCenterResource.judgeUserJurisdiction(queryModel, true);
        List<Map<String, Object>> list = new ArrayList<>();
        list = networkLiabilityStatementsService.getNetworkLiabilityStatementsInfo(queryModel);
        return new ResultDto<>(list);
    }

    @GetMapping("/exportExcel")
    public ResultDto<String> exportExcel(QueryModel queryModel) {
        CustCenterResource.judgeUserJurisdiction(queryModel, true);
        String taskId = excelTaskManager.addExcelExportTask(exportSql, null, queryModel, pojoClassName);
        return new ResultDto<>(taskId);
    }

    @GetMapping("/queryDownloadInfo")
    public ResultDto<Map<String,Object>> queryInfo(@RequestParam("taskId") String taskId) throws JsonException {
        ResultDto<Map<String, Object>> resultDto = new ResultDto<>();
        HashMap<String, Object> map = new HashMap<>();
        resultDto.setData(map);
        JSONObject jo = ExcelImportExportUtil.getRedisTaskInfo(taskId, stringRedisTemplate);
        Iterator<String> keys = jo.keys();
        while (keys.hasNext()){
            String key = keys.next();
            map.put(key,jo.get(key));
        }
        return resultDto;
    }

    @GetMapping("/downloadDepExcel")
    public void downloadDep(String taskId,HttpServletResponse response, HttpServletRequest request){
        OutputStream os=null;
        FileManagementClient fastDFClient=fileManagementClientFactory.getFileManagementClient();
        try {
            //通过taskId从Redis中拿到任务执行信息
            JSONObject jo = ExcelImportExportUtil.getRedisTaskInfo(taskId, stringRedisTemplate);
            int percent = jo.getInt(ExcelConstant.REDIS_PERCENT_KEY);
            if (100 == percent){
                String fileName=jo.getString(ExcelConstant.REDIS_FILENAME_KEY).toString();
                String fileUuid = jo.get(ExcelConstant.REDIS_FASTDFS_KEY).toString();
                if (StringUtils.isEmpty(fileUuid)){
                    System.out.println(ExcelConstant.REDIS_FILENAME_KEY+"is null !");
                }
                String userAgent = request.getHeader("user-agent").toLowerCase();
                if (userAgent.contains("msie")||userAgent.contains("like gecko")){
                    //win10 ie edge 浏览器 和 其他系统的ie
                    fileName = URLEncoder.encode(fileName,"UTF-8");
                }else{
                    fileName= new String(fileName.getBytes("UTF-8"),"iso-8859-1");
                }
                //获取文件
                fastDFClient.initConnection();
                byte[] downloadFile=fastDFClient.downloadFile(fileUuid);
                //写出文件
                response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
                response.setCharacterEncoding("UTF-8");
                response.setHeader("Content-disposition","attachment;filename="+fileName);
                os=response.getOutputStream();
                os.write(downloadFile);
                os.flush();
            }else{
                System.out.println(ExcelConstant.REDIS_PERCENT_KEY + "is not 100,正在异步导出中,不能下载");
            }
        }catch(Exception e){
            System.out.println("出错:"+e.toString());
        }finally {
            fastDFClient.closeConnection();
            if (os!=null){
                try{
                    os.close();
                }catch (Exception e){
                    System.out.println("出错:"+e.toString());
                }
            }
        }
    }



}
